/*
*编辑复合基准
*EditBenchmark.js*/

import React, {Component,PureComponent} from 'react';
import { Modal, Button,Form, Row,Col,Input, Select, Icon,message,Radio} from 'antd';
import { connect } from 'react-redux';
import style from './editBenchmark.less';
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
class CompoundDatum extends React.Component {
  constructor(props) {
    super(props);
    console.log(887766,this.props,props)
    const value = this.props.value||{} ;
    this.state = {
      benchmarkRate: value.benchmarkRate || '',
      benchmarkCode: value.benchmarkCode || '',
      benchmarkName:value.benchmarkName  || ''
    };
  }

  handleNumberChange = (e) => {
    const benchmarkRate = parseInt(e.target.value || 0, 10);
    console.log(11233,benchmarkRate)
    if (isNaN(benchmarkRate)) {
      return;
    }
    this.setState({ benchmarkRate });
    this.triggerChange({ benchmarkRate });
  }

  handleCurrencyChange = (benchmarkCode) => {
    
    this.setState({ benchmarkCode });
    this.triggerChange({ benchmarkCode });
  }

  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, this.state, changedValue));
    }

    console.log(44556677,changedValue,this.props,this.state)
  }
  
  render() {
    const {BenchmarkList} = this.props;
    console.log(4322,this.props)

    const state = this.state;
    return (
      <Row type="flex" justify="start">
        <Col span={7}>
          <Input
            type="text"
            value={state.benchmarkRate}
            onChange={this.handleNumberChange}
            addonAfter="%"
            style={{width:100}}
          />
        </Col>
        <Col span={10}>
          <Select
          	defaultValue={`${state.benchmarkCode}-${state.benchmarkName}` || ''}
            value={state.benchmarkCode}
            onChange={this.handleCurrencyChange}
            allowClear={true}
            placeholder="请选择基准"
            style={{width:150}}
          >
            {
              BenchmarkList.map((item,i)=><Option value={`${item.benchCode}`} key={i}>{item.benchCode}-{item.benchName}</Option>)
            }
          </Select>
        </Col>
      </Row>
    );
  }
}
let uuid = 0 ;
const EditBenchmarkForm = Form.create()(
  class extends React.Component {
    baseRatechange=(e)=>{
      const baseRate = parseInt(e.target.value || 0, 10);
      console.log(11233,baseRate)
      if (isNaN(baseRate)) {
        return;
      }
      data.dispatch({
        type:`benchmarkMgt/setState`,
        payload:{
          'baseRate':baseRate,
        }
      })
    }
    remove = (k) => {
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      if (keys.length === 0) {
        return;
      }
      form.setFieldsValue({
        keys: keys.filter(key => key !== k),
      });
    }

    add = (v) => {
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      const nextKeys = keys.concat(uuid + v-1);
      console.log(56722111,keys,nextKeys,v)
      if(nextKeys.length < 4){
        uuid++;
        form.setFieldsValue({
          keys: nextKeys,
        });
      }else{
        message.warning('复合基准最多4个')
      }
      
    }
    componentDidMount() {
    	const { data} = this.props;
    	if(!_.isEmpty(data.data.weight)){
    		data.data.weight.map(i=>{
      		const a = i.benchmarkRate * 100;
          i.benchmarkRate = parseInt(a)
      	})
    	}
    }
    render() {
      const { visible, onCancel, onCreate, form ,data} = this.props;
      const { getFieldDecorator, getFieldValue } = this.props.form;
      // getFieldDecorator('keys', { initialValue: [] });
      
      console.log(34500,data)
      if(_.isEmpty(data.data.weight)){
      	return(
      		visible ?
	        <Modal
	          visible={visible}
	          title="编辑"
	          okText="提交"
	          cancelText="取消"
	          onCancel={onCancel}
	          onOk={onCreate}
	        >
	      		<Form>
							<FormItem
								label="基准名称"
							>
								{getFieldDecorator(
									'benchName',
									{
										rules: [
										  { required: true, message: '请输入基准名称!' },
										],
										initialValue: data.data.benchName,
									},
								)(
									<Input disabled />,
								)}
							</FormItem>
							<FormItem
								label="描述"
							>
								{getFieldDecorator(
									'description',
									{
										initialValue: data.data.description,
									},
								)(
									<Input />,
								)}
							</FormItem>
						</Form>
					</Modal>:null
      	)
      }else{
      	const len = data.data.weight.length;
      	
      	if(len == 2){

      		getFieldDecorator('keys', { initialValue: [0] });
		      const keys = getFieldValue('keys');
		      const formItems = keys.map((k, index) => {
		        return (
		          <FormItem
		            required={false}
		            key={k}
		          >
		            {getFieldDecorator(`jizhuns[${k}]`, {
		              rules: [{
		                required: true,
		                message: "请选择基准或输入权重",
		              }],
		              initialValue: data.data.weight[k+1],
		            })(
		              <CompoundDatum 
		              	BenchmarkList={data.BenchmarkList}
		              />
		            )}
		            {keys.length > 0 ? (
		              <Icon
		                className="dynamic-delete-button"
		                type="minus-circle-o"
		                onClick={() => this.remove(k)}
		              />
		            ) : null}
		          </FormItem>
		        );
		      });
		      return(
	      		visible ?
		        <Modal
		          visible={visible}
		          title="编辑"
		          okText="提交"
		          cancelText="取消"
		          onCancel={onCancel}
		          onOk={onCreate}
		        >
		      		<Form layout="vertical" className={style.benchStyle}>
								<FormItem
									label="基准名称"
								>
									{getFieldDecorator(
										'benchName',
										{
											rules: [
											  { required: true, message: '请输入基准名称!' },
											],
											initialValue: data.data.benchName,
										},
									)(
										<Input/>,
									)}
								</FormItem>
								<FormItem
		              label="基准"
		            >
		              {getFieldDecorator(`jizhun`, {
		                validateTrigger: ['onChange', 'onBlur'],
		                rules: [{
		                  required: true,
		                  message: "请选择基准或输入权重",
		                }],
		                initialValue: data.data.weight[0],
		              })(
		                <CompoundDatum 
		                	BenchmarkList={data.BenchmarkList}
		                	
		                />
		              )}
		              {(
		                <Icon
		                  className="dynamic-delete-button"
		                  type="plus-circle-o"
		                  onClick={()=>this.add(data.data.weight.length)}
		                />
              		)}
            		</FormItem>
								{formItems}
								<FormItem
		              label="绝对收益"
		            >
		              {getFieldDecorator(`baseRate`, {
		                initialValue: data.baseRate,
		                rules: [
		                  { whitespace: true,required: true, pattern:/^([1-9]\d*|[0]{1,1})$/, message: '请输入数字!' },
		                ],
		                initialValue: data.data.baseRate*100,
		              })(
		                <Input
		                  addonAfter="%"
		                  style={{width:100}}
		                />
              	)}
            		</FormItem>
            		<FormItem
		              label="个人&公用标签"
		            >
		              {getFieldDecorator('isShare',{
		                rules: [{
		                  required: true,
		                  message: "请选择是否公开",
		                }],
		                initialValue:`${data.data.isShare}` ,
		              })(
		                <RadioGroup>
		                  <Radio value="0">个人标签</Radio>
		                  <Radio value="1">公用标签</Radio>
		                </RadioGroup>
		              )}
            		</FormItem>
								<FormItem
									label="描述"
								>
									{getFieldDecorator(
										'description',
										{
											initialValue: data.data.description,
										},
									)(
										<Input/>,
									)}
								</FormItem>
							</Form>
						</Modal>:null
      		)	
      	}else if(len ==3){
      		getFieldDecorator('keys', { initialValue: [0,1] });
		      const keys = getFieldValue('keys');
		      const formItems = keys.map((k, index) => {
		        return (
		          <FormItem
		            required={false}
		            key={k}
		          >
		            {getFieldDecorator(`jizhuns[${k}]`, {
		              rules: [{
		                required: true,
		                message: "请选择基准或输入权重",
		              }],
		              initialValue: data.data.weight[k+1],
		            })(
		              <CompoundDatum 
		              	BenchmarkList={data.BenchmarkList}
		              />
		            )}
		            {keys.length > 0 ? (
		              <Icon
		                className="dynamic-delete-button"
		                type="minus-circle-o"
		                onClick={() => this.remove(k)}
		              />
		            ) : null}
		          </FormItem>
		        );
		      });
		      return(
	      		visible ?
		        <Modal
		          visible={visible}
		          title="编辑"
		          okText="提交"
		          cancelText="取消"
		          onCancel={onCancel}
		          onOk={onCreate}
		        >
		      		<Form layout="vertical" className={style.benchStyle}>
								<FormItem
									label="基准名称"
								>
									{getFieldDecorator(
										'benchName',
										{
											rules: [
											  { required: true, message: '请输入基准名称!' },
											],
											initialValue: data.data.benchName,
										},
									)(
										<Input/>,
									)}
								</FormItem>
								<FormItem
		              label="基准"
		            >
		              {getFieldDecorator(`jizhun`, {
		                validateTrigger: ['onChange', 'onBlur'],
		                rules: [{
		                  required: true,
		                  message: "请选择基准或输入权重",
		                }],
		                initialValue: data.data.weight[0],
		              })(
		                <CompoundDatum 
		                	BenchmarkList={data.BenchmarkList}
		                />
		              )}
		              {(
		                <Icon
		                  className="dynamic-delete-button"
		                  type="plus-circle-o"
		                  onClick={()=>this.add(data.data.weight.length)}
		                />
              		)}
            		</FormItem>
								{formItems}
								<FormItem
		              label="绝对收益"
		            >
		              {getFieldDecorator(`baseRate`, {
		                initialValue: data.baseRate,
		                rules: [
		                  { whitespace: true,required: true, pattern:/^([1-9]\d*|[0]{1,1})$/, message: '请输入数字!' },
		                ],
		                initialValue: data.data.baseRate*100,
		              })(
		                <Input
		                  addonAfter="%"
		                  style={{width:100}}
		                />
              	)}
            		</FormItem>
            		<FormItem
		              label="个人&公用标签"
		            >
		              {getFieldDecorator('isShare',{
		                rules: [{
		                  required: true,
		                  message: "请选择是否公开",
		                }],
		                initialValue: `${data.data.isShare}`,
		              })(
		                <RadioGroup>
		                  <Radio value="0">个人标签</Radio>
		                  <Radio value="1">公用标签</Radio>
		                </RadioGroup>
		              )}
            		</FormItem>
								<FormItem
									label="描述"
								>
									{getFieldDecorator(
										'description',
										{
											initialValue: data.data.description,
										},
									)(
										<Input/>,
									)}
								</FormItem>
							</Form>
						</Modal>:null
      		)	
      	}else if(len == 4){
      		getFieldDecorator('keys', { initialValue: [0,1,2] });
		      const keys = getFieldValue('keys');
		      const formItems = keys.map((k, index) => {
		        return (
		          <FormItem
		            required={false}
		            key={k}
		          >
		            {getFieldDecorator(`jizhuns[${k}]`, {
		              rules: [{
		                required: true,
		                message: "请选择基准或输入权重",
		              }],
		              initialValue: data.data.weight[k+1],
		            })(
		              <CompoundDatum 
		              	BenchmarkList={data.BenchmarkList}
		              />
		            )}
		            {keys.length > 0 ? (
		              <Icon
		                className="dynamic-delete-button"
		                type="minus-circle-o"
		                onClick={() => this.remove(k)}
		              />
		            ) : null}
		          </FormItem>
		        );
		      });
		      return(
	      		visible ?
		        <Modal
		          visible={visible}
		          title="编辑"
		          okText="提交"
		          cancelText="取消"
		          onCancel={onCancel}
		          onOk={onCreate}
		        >
		      		<Form layout="vertical" className={style.benchStyle}>
								<FormItem
									label="基准名称"
								>
									{getFieldDecorator(
										'benchName',
										{
											rules: [
											  { required: true, message: '请输入基准名称!' },
											],
											initialValue: data.data.benchName,
										},
									)(
										<Input/>,
									)}
								</FormItem>
								<FormItem
		              label="基准"
		            >
		              {getFieldDecorator(`jizhun`, {
		                validateTrigger: ['onChange', 'onBlur'],
		                rules: [{
		                  required: true,
		                  message: "请选择基准或输入权重",
		                }],
		                initialValue: data.data.weight[0],
		              })(
		                <CompoundDatum 
		                	BenchmarkList={data.BenchmarkList}
		                />
		              )}
		              {(
		                <Icon
		                  className="dynamic-delete-button"
		                  type="plus-circle-o"
		                  onClick={()=>this.add(data.data.weight.length)}
		                />
              		)}
            		</FormItem>
								{formItems}
								<FormItem
		              label="绝对收益"
		            >
		              {getFieldDecorator(`baseRate`, {
		                initialValue: data.baseRate,
		                rules: [
		                  { whitespace: true,required: true, pattern:/^([1-9]\d*|[0]{1,1})$/, message: '请输入数字!' },
		                ],
		                initialValue: data.data.baseRate*100,
		              })(
		                <Input
		                  addonAfter="%"
		                  style={{width:100}}
		                />
              	)}
            		</FormItem>
            		<FormItem
		              label="个人&公用标签"
		            >
		              {getFieldDecorator('isShare',{
		                rules: [{
		                  required: true,
		                  message: "请选择是否公开",
		                }],
		                initialValue: `${data.data.isShare}`,
		              })(
		                <RadioGroup>
		                  <Radio value="0">个人标签</Radio>
		                  <Radio value="1">公用标签</Radio>
		                </RadioGroup>
		              )}
            		</FormItem>
								<FormItem
									label="描述"
								>
									{getFieldDecorator(
										'description',
										{
											initialValue: data.data.description,
										},
									)(
										<Input/>,
									)}
								</FormItem>
							</Form>
						</Modal>:null
      		)
      	}else{
      		return null;
      	}
    	
      }
    }
  }
);
let weight;
class EditBenchmark extends React.Component {
  state = {
    visible: false,
  };

  showModal = () => {
    this.setState({ visible: true });
  }

  handleCancel = () => {
    const form = this.formRef.props.form;
    this.setState({ visible: false });
    form.resetFields();
  }
  handleCreate = () => {
    const form = this.formRef.props.form;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      console.log(33333,this.props)
      console.log('Received values of form: 1111', values);
      for(var i = 0 ;i<values.jizhuns.length;i++) {
        if(values.jizhuns[i] == "" || typeof(values.jizhuns[i]) == "undefined"){
          values.jizhuns.splice(i,1);
          i= i-1;
        }
      }
      if(!values.jizhuns){
        message.warning('复合基准至少为2个最多4个');
        this.setState({ visible: true });
      }else if(values.jizhuns){
        values.jizhuns.push(values.jizhun);
        for(let i=0;i<values.jizhuns.length;i++){
          if(values.jizhuns[i].benchmarkRate == NaN || 
            values.jizhuns[i].benchmarkRate == undefined){
            message.warning('请输入权重');
            this.setState({ visible: true });
            return;
          }else if(values.jizhuns[i].benchmarkCode == undefined){
            message.warning('请选择基准');
            this.setState({ visible: true });
            return;
          }else if(values.jizhuns[i].benchmarkRate !== NaN && values.jizhuns[i].benchmarkRate !== undefined&&
            values.jizhuns[i].benchmarkCode !== undefined){
            for(let j=i+1;j<values.jizhuns.length;j++){
              if(values.jizhuns[i].benchmarkCode == values.jizhuns[j].benchmarkCode){
                message.warning('存在相同基准,请选择不同基准');
                return;
                this.setState({ visible: true });
              }else{
                weight = values.jizhuns;
              }
            }
          }
        }
      }
      if(!_.isEmpty(weight)){
        weight.map((item)=>{
          const a =item.benchmarkRate / 100;
          item.benchmarkRate = a
        })
        const querys = {};
        if(this.props.data.benchName !== values.benchName){
        	querys.benchName = values.benchName;
        }
        querys.weight = weight;
        querys.baseRate = values.baseRate / 100;
        querys.benchId = this.props.data.benchId;
        querys.isShare = values.isShare;
        values.description&&(querys.description = values.description);
        this.props.dispatch({
          type:`benchmarkMgt/editBenchmark`,
          payload:{
            ...querys
          }
        })
        this.setState({ visible: false });
        form.resetFields();
      }
        
    });
  }

  saveFormRef = (formRef) => {
    this.formRef = formRef;
  }
  render() {
    return (
      <div>
        <a type="primary" onClick={this.showModal}>编辑</a>
        <EditBenchmarkForm
          wrappedComponentRef={this.saveFormRef}
          visible={this.state.visible}
          onCancel={this.handleCancel}
          onCreate={this.handleCreate}
          data={this.props}
        />
      </div>
    );
  }
}
EditBenchmark.defaultProps={

}
export default connect()(EditBenchmark)